package com.pig4cloud.pigx.knowledge.config;

import com.pig4cloud.pigx.knowledge.config.properties.AiKnowledgeProperties;
import com.pig4cloud.pigx.knowledge.service.MiIotHomeAssistantService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.support.RestClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

/**
 * 小米物联网配置
 *
 * @author lengleng
 * @date 2024/12/22
 */
@Configuration(proxyBeanMethods = false)
public class MiIotConfiguration {

    /**
     * 家居助理服务
     *
     * @param restClientBuilder   REST 客户端构建器
     * @param knowledgeProperties 配置
     * @return {@link MiIotHomeAssistantService }
     */
    @Bean
    public MiIotHomeAssistantService homeAssistantService(RestClient.Builder restClientBuilder, AiKnowledgeProperties knowledgeProperties) {
        RestClient client = restClientBuilder
                .requestFactory(new JdkClientHttpRequestFactory())
                .baseUrl(knowledgeProperties.getMiIot().getBaseUrl())
                .defaultHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", knowledgeProperties.getMiIot().getApiKey()))
                .build();

        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(RestClientAdapter.create(client)).build();
        return factory.createClient(MiIotHomeAssistantService.class);
    }
}
